package com.mm.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * 日期工具类
 */
public class DateUtils {

    public static final String PATTEN_YMD_HMS = "yyyy-MM-dd HH:mm:ss";
    public static final String PATTEN_YMD = "yyyy-MM-dd";
    public static final String PATTEN_YMD1 = "yyyy/MM/dd";
    public static final String PATTEN_YMD_HMS1 = "yyyy/MM/dd HH:mm:ss";

    /**
     * 把long类型日期转化为格式化字符串日期
     *
     * @param longTimeStamp long类型时间戳
     * @param pattern       格式
     * @return String(格式化后的日期)
     */
    public static String longTimeStampToStringDate(Long longTimeStamp, String pattern) {
        if (longTimeStamp == null || StringUtils.isBlank(pattern)) {
            throw new NullPointerException("时间戳或格式类型不能为空");
        }
        Date date = new Date(longTimeStamp);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String formatDate = simpleDateFormat.format(date);
        return formatDate;
    }

    /**
     * 把字符串日期转换为LonG类型日期
     *
     * @param time    字符串日期
     * @param pattern 格式
     * @return Long日期
     * @throws ParseException
     */
    public static Long stringTimeToLongTimeStamp(String time, String pattern) throws ParseException {
        if (StringUtils.isBlank(time) || StringUtils.isBlank(pattern)) {
            throw new NullPointerException("时间或格式类型不能为空");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Long formateDate = simpleDateFormat.parse(time).getTime();
        return formateDate;
    }

    /**
     * 时间范围转换为开始时间和结束时间
     *
     * @param dateRange 时间范围
     * @return HashMap<Object ,   O bject>
     */
    public static HashMap<Object, Long> dateRangeToString(String dateRange, String pattern) throws ParseException{
        HashMap<Object, Long> resultMap = new HashMap<>(2);
        Long startTime = null;
        Long endTime = null;
        if(StringUtils.isNotBlank(dateRange)) {
            String[] dateRangeArr = dateRange.split("-");
            String startTimeStr = dateRangeArr[0];
            String endTimeStr = dateRangeArr[1];
            if (StringUtils.isNotBlank(startTimeStr)) {
                startTime = stringTimeToLongTimeStamp(startTimeStr, pattern);
                endTime = stringTimeToLongTimeStamp(endTimeStr, pattern);
			}
		}
        resultMap.put("startTime", startTime);
        resultMap.put("endTime", endTime);
        return resultMap;
	}

    /**
     * 获取任意时间下一个月
     *
     * @param dateL 任意时间
     * @return
     */
    public static Long getPreMonth(Long dateL) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dateL);
        cal.add(Calendar.MONTH, 1);
        return cal.getTimeInMillis();
    }
}